<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
         <!-- 卡片 -->
         <el-card>
             <el-row>
                 <el-button type="primary" @click="showAddRole=true">添加角色</el-button>
             </el-row>
           <!-- 表单 -->
            <el-table :data="rolesList" border style="width: 100%" stripe>
                <!-- 展开列 -->
                <el-table-column type="expand">
                     <template slot-scope="scope">
                        <el-row v-for="(item1,i1) in scope.row.children" :key="item1.id" :class="['bdbottom',i1 === 0?'bdtop':'','vcenter']">
                            <!-- 一级 -->
                            <el-col :span="5">
                                <el-tag closable @close='delTag(scope.row,item1.id)'>
                                    {{item1.authName}}
                                </el-tag>
                                 <i class="el-icon-caret-right"></i>
                            </el-col>
                             <!-- 二级和三级 -->
                            <el-col :span="19">
                                <!-- 二级 -->
                                <el-row v-for="(item2,i2) in item1.children" :key="item2.id" :class="[i2 === 0?'':'bdtop','vcenter']">
                                  <el-col :span="6">
                                    <el-tag type="success" closable @close='delTag(scope.row,item2.id)'>
                                        {{item2.authName}}
                                    </el-tag>  
                                       <i class="el-icon-caret-right"></i> 
                                  </el-col>
                                  <!-- 三级 -->
                                  <el-col :span="18"> 
                                      <el-tag v-for="item3 in item2.children" :key="item3.id" closable @close='delTag(scope.row,item3.id)'>
                                          {{item3.authName}}
                                      </el-tag>
                                  </el-col>
                                </el-row>                            
                            </el-col>
                        </el-row>
                     </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="roleName" label="角色"></el-table-column>
                <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="small" @click="revRoles(scope.row)">编辑</el-button>
                        <el-button type="danger" icon="el-icon-share" size="small" @click="delRoles(scope.row.id)">删除</el-button>
                        <el-button type="warning" icon="el-icon-setting" size="small" @click="setRoles(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
         </el-card>
         <!-- 权限管理 -->
        <el-dialog
        title="分配权限"
        :visible.sync="showRoles"
        width="30%"
        @close='setClose'
        >
        <!-- 树形控件 -->
        <el-tree :data="rightsList" 
        :props="terrProps" 
        show-checkbox 
        default-expand-all 
        node-key='id' 
        :default-checked-keys='arrKeys'
        ref="treeRef"
        ></el-tree>
        <span slot="footer" class="dialog-footer">
            <el-button @click="showRoles = false">取 消</el-button>
            <el-button type="primary" @click="addRight">确 定</el-button>
        </span>
        </el-dialog>
        <!-- 添加角色对话框 -->
        <el-dialog
        title="添加角色"
        :visible.sync="showAddRole"
        width="50%">
        <el-form :model="addForm" :rules="addFormRules" ref="rolesFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
         <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="showAddRole = false">取 消</el-button>
            <el-button type="primary" @click="addRoles">确 定</el-button>
        </span>
        </el-dialog>
        <!-- 编辑角色对话框 -->
        <el-dialog
        title="编辑角色"
        :visible.sync="showRev"
        width="50%">
        <el-form :model="revForm" :rules="revFormRules" ref="revFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="revForm.roleName"></el-input>
        </el-form-item>
         <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="revForm.roleDesc"></el-input>
        </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="showRev = false">取 消</el-button>
            <el-button type="primary" @click="revRolesList">确 定</el-button>
        </span>
        </el-dialog>
    </div>
</template>

<script>
import rightsVue from './rights.vue'
export default {
    data () {
        return {
            //角色列表数据
            rolesList:[],
           // 权限管理窗口默认样式
            showRoles:false,
            //权限列表数据
            rightsList:[],
            //树形控件的属性绑定
            terrProps:{
                //展示的类容区域
               children: 'children',
               //展示的文本
               label: 'authName'
            },
            //放选中树形图id的数组
            arrKeys:[],
            //当前即将分配权限的角色id
            roleId:'',
           //添加角色对话框状态
           showAddRole:false,
        // 添加表单的数据   
           addForm:{},
         //添加表单效验
           addFormRules:{
               roleName:[
                      { required: true, message: '请输入角色名称', trigger: 'blur' },
                      { min: 5, max: 12, message: '长度在 5 到 12 个字符', trigger: 'blur' }
               ],
               roleDesc:[
                      { required: true, message: '请输入角色描述', trigger: 'blur' },
                      { min: 5, max: 12, message: '长度在 5 到 12 个字符', trigger: 'blur' }
               ]
           },
           //编辑角色对话框默认状态
           showRev:false,
           //编辑表单的数据
           revForm:{},
           //编辑表单效验
           revFormRules:{
               roleName:[
                      { required: true, message: '请输入角色名称', trigger: 'blur' },
                      { min: 2, max: 12, message: '长度在 2 到 12 个字符', trigger: 'blur' }
               ],
               roleDesc:[
                      { required: true, message: '请输入角色描述', trigger: 'blur' },
                      { min: 2, max: 12, message: '长度在 2 到 12 个字符', trigger: 'blur' }
               ]               
           }
        }
    },
    created () {
        this.getrolesList ()
    },
    methods:{
      async getrolesList () {
         const res = await this.$http.get('roles')
         if(res.data.meta.status == 200){
           this.rolesList = res.data.data
           console.log(this.rolesList)
         }else{
            return this.$message.error('角色列表请求失败');
         }
       },
      async delTag (did,id) {
         const dalConfirm = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
          if(dalConfirm=='cancel'){
             return this.$message.info('取消删除');
          }else{                      
            const res = await this.$http.delete(`roles/${did.id}/rights/${id}`)
            console.log(res)
            if(res.data.meta.status == 200 ){
                 this.$message.success('删除成功')
                //  this.getrolesList()
                did.children = res.data.data
            }
          }         
       },
       //获取权限数据树形图
      async setRoles (role) {
          this.roleId = role.id
          const res = await this.$http.get('rights/tree')
          if(res.data.meta.status == 200){
             this.rightsList = res.data.data
             //在对话框展开之前调用三级对话框
             this.getListKeys(role,this.arrKeys)
             this.showRoles = true
             console.log(this.rightsList)
          }else{
              return this.$message.error('权限列表请求失败');
          }
       },
    //    获取所以三级权限的id，因为获取三级会自动勾选父级权限
       getListKeys (node,arr) {
        // 方法1递归看不太懂
        //   if(!node.children){
        //      return arr.push(node.id)
        //   }
        //   node.children.forEach(item=>{
        //       return this.getListKeys(item,arr)
        //   })
        //方法2镶嵌3层我直接循环3层
        node.children.forEach( item1 => {
             item1.children.forEach( item2 =>{
                item2.children.forEach (item3 =>{
                    return arr.push(item3.id)
                })
             })
        });
       },
       //关闭分配权限对话框重置数组
       setClose () {
           this.arrKeys = []
       },
       //点击分配权限的确定按钮
      async addRight () {
         //1获取所有全选和半选的id:getCheckedKeys()组件提供的全选状态的方法
         //                      getHalfCheckedNodes() 组件提供的半选状态的方法
         const keys = [...this.$refs.treeRef.getCheckedKeys(),...this.$refs.treeRef.getHalfCheckedNodes()]
         console.log(keys)
         //接口中要求传字符串
        const idStr = keys.join(',')
        const res = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
        console.log(res)
        if(res.data.meta.status == 200){
           this.$message.success('修改权限成功')
           this.getrolesList()
           this.showRoles = false
        }else{
            return this.$message.error('修改权限失败');
        }
       },
       addRoles () {
           this.$refs.rolesFormRef.validate(async valid=>{
               if(!valid){
                  return
               }else{
                   const res = await this.$http.post('roles',this.addForm)
                   console.log(res)
                   if(res.data.meta.status == 201){
                       this.$message.success('添加成功')
                       this.getrolesList()
                       this.showAddRole = false
                   }else{
                       return this.$message.error('添加失败');
                   }
               }
           })
       },
      async delRoles (id) {
         const confirm = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        console.log(confirm)
         if(confirm=='cancel'){
           return this.$message.info('取消删除');
         }else{
             const res = await this.$http.delete('roles/'+id)
             if(res.data.meta.status == 200){
                 this.$message.success('删除成功')
                 this.getrolesList()
             }else{
                 return this.$message.error('删除失败');
             }
         }
       },
       //编辑角色
       revRoles (data) {
          this.revForm = data
          this.showRev = true
       },
       //点击编辑角色确定按钮
       revRolesList () {
         this.$refs.revFormRef.validate(async valid=>{
             if(!valid){
                return
             }else{
                  const res = await this.$http.put('roles/'+this.revForm.id,
                  {roleName:this.revForm.roleName,
                   roleDesc:this.revForm.roleDesc
                  })
                  if(res.data.meta.status == 200){
                      this.$message.success('修改用户成功')
                      this.getrolesList()
                      this.showRev = false
                  }else{
                      return this.$message.error('修改用户失败');
                  }
             }
         })
       }
    }
}
</script>

<style lang="less" scoped>
     .el-tag {
         margin: 7px;
     }
     .bdtop{
       border-top: 1px solid #eee;
     }
     .bdbottom{
          border-bottom: 1px solid #eee;
     }
     .vcenter{
         display: flex;
         align-items: center;
     }
</style>